package org.remixlab.gnutopic.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XmlSolrHandler extends DefaultHandler {
	
	private String value;
	private String name;
	
	private String temp = "";
	
	private Map<String, ArrayList<Integer>> threads = new HashMap <String, ArrayList<Integer>> ();
	
	public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
		
		if(qName.equalsIgnoreCase("str")){
			if(attributes!=null && attributes.getLength()>0){
				int length = attributes.getLength();
				
				for (int i=0; i<length; i++) {
					
					name = attributes.getQName(i);
		            value = attributes.getValue(i);
					temp = "";
					
					//System.out.println("start element:"+qName+" name: "+name+" value: "+value);	
				}
			}
		}
		
	}
	
	public void characters(char ch[], int start, int length) throws SAXException {
		//System.out.println("characters: "+new String(ch, start, length));
		temp = temp + new String(ch, start, length);
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName.equalsIgnoreCase("str")){
			if(value.equalsIgnoreCase("id")){
				//si es igual al id, entonces en temp esta el id del hilo..
				int i = temp.indexOf(".");
				
				//primero obtengo el id, del tread.
				if(i>0){
					//obtengo el id del thread..
					String threadId = temp.substring(0,i);
					
					//obtengo el id del mensaje..
					String strMessageId = temp.substring(i+1);
					
					ArrayList<Integer> messages = threads.get(threadId);
					
					//si es diferente de nulo, entonces agrego el mensaje.
					if(messages!=null){
						messages.add(Integer.parseInt(strMessageId));
					}else{
						//creo el arraylist y lo agrego al hashMap
						messages = new ArrayList<Integer> ();
						
						//agrego el mensaje..
						messages.add(Integer.parseInt(strMessageId));
						
						//agrego el arraylist al HashMap
						threads.put(threadId, messages);
					}
					
					System.out.println("temp: "+temp+" id:"+threadId+ " message: "+strMessageId);
					
				}
			}
		}
		
	}

	public Map<String, ArrayList<Integer>> getThreads() {
		return threads;
	}

	public void setThreads(Map<String, ArrayList<Integer>> threads) {
		this.threads = threads;
	}

}
